try:
    from xml.etree import cElementTree as etree
except ImportError:
    from xml.etree import ElementTree as etree

from zope.interface import implements, directlyProvides

from meercat.harvester.sfx.interfaces import *



class SimpleTag(object):
    implements(ISFXTagField)
    def __init__(self, tag, attributes=[], filter=None):
        """ Attributes should be a list of attributes in "key:value" format. """
        self.tag = tag
        self.attributes = attributes
        self.filter = filter
    
    def setAttributes(self, attributes):
        if attributes is None:
            attributes = []
        
        self._attributes = dict(map(lambda a: a.split(':',1), attributes))
        
    def getAttributes(self):
        return self._attributes
    
    attributes = property(getAttributes, setAttributes)
    
    def __call__(self, value):
        if self.filter:
            value = self.filter(value)
        if not value:
            return None
        element = etree.Element(self.tag, self.attributes)
        element.text = value
        return element

class TokenizedTag(SimpleTag):
    implements(ISFXTokenizedTagField)
    def __init__(self, tokenizer, **kwargs):
        super(TokenizedTag, self).__init__(**kwargs)
        assert callable(tokenizer)
        self.tokenizer = tokenizer
    
    def __call__(self, value):
        return filter(lambda v: v is not None,
                      map(super(TokenizedTag, self).__call__,
                          self.tokenizer(value)))


class MapFilter(object):
    implements(ISFXFilter)
    
    def __init__(self, mapping, **kwargs):
        self._map = mapping
        if 'default' in kwargs:
            self.default = kwargs['default']
    
    def __call__(self, value):
        if hasattr(self,'default'):
            return self._map.get(value, self.default)
        
        if value in self._map:
            return self._map[value]
        
        return value

def stripFilter(value):
    return value.strip()

directlyProvides(stripFilter, ISFXFilter)

class SplitTokenizer(object):
    implements(ISFXTokenizer)
    
    def __init__(self, separator):
        self.separator = separator
    
    def __call__(self, value):
        return value.split(self.separator)

categoryTokenizer = SplitTokenizer('|')

